package dk.itu.spvc.bluefriends;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import dk.itu.spvc.bluefriends.classes.Constant;
import dk.itu.spvc.bluefriends.classes.Profile;


public class FriendActivity extends BlueFriends{

	private static final String TAG = FriendActivity.class.getSimpleName();
	private String[] proj;
	private ListView friendList,memberList;
	private TextView friends,peers;
	private boolean stop=false;
	private Thread updating=null;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        setContentView(R.layout.friend);
        friendList=(ListView)findViewById(R.id.friendList);
        friends=(TextView)findViewById(R.id.friends);
        
        memberList=(ListView)findViewById(R.id.memberList);
        memberList.setVisibility(4);
        peers=(TextView)findViewById(R.id.Members);
        peers.setVisibility(4);
        
        members.add(myProfile);
        proj = new String[]{
				BaseColumns._ID,
				Constant.USERNAME,
				Constant.GENDER,
				Constant.MACADDR,
				Constant.EMAIL,
				Constant.ISPENDING,
				Constant.TIMESTAMP
		};
        Cursor c = managedQuery(Constant.PROFILE_CONTENT_URI, proj, "ISPENDING LIKE 'false'", null,null);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.frienditem, c, 
				new String[]{Constant.USERNAME,Constant.GENDER,Constant.MACADDR,Constant._ID}, 
				new int[]{R.id.name,R.id.gender,R.id.mac,R.id.friendId}
		);
		friendList.setAdapter(adapter);
		Log.d(TAG,"oncreate called");
	}
	
	public void onResume(){
		super.onResume();
		stop=false;
		if(updating==null && memberList.getVisibility()==0)getMembersInfo();
	}
	
	public void setMemberList(){
		memberList.setAdapter((ListAdapter) new ArrayAdapter<Profile>(
				this,R.layout.memberitem,R.id.memberInfo, members));
	}
	

	public void getMembersInfo(){
		final ProgressDialog dialog = ProgressDialog.show(this, "", 
                "Loading. Please wait...", true);
		updating=new Thread(new Runnable(){
			@Override
			public void run() {
				while(!Thread.interrupted() && !stop){					
					Log.d(TAG,"updating all member info thread started");
					try {
						//send out request to get members info
						String[] devices= beddernetService.getDevices(applicationIdentifier);
						beddernetService.sendMulticast(devices, null, 
								(MEMBERINFO+"|").getBytes(), applicationIdentifier);
					} catch (RemoteException e) {
						Log.e(TAG,"erros on get devices from service, is the bluetooth device discoverable?");
					}
					
					try {
						//wait for 3 sec.
						Thread.sleep(3000);
						dialog.cancel();
						memberList.post(new Runnable(){
							@Override
							public void run() {	
								setMemberList();
							}
						});
						Thread.sleep(5000);
						members.clear();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				Log.d(TAG,"updating all member info thread ended");
			}
		});
		updating.start();
	}
	
	public void addAsFriend(View v){
		//send request....
		Button b=(Button)v;
		b.setEnabled(false);
		TextView t=(TextView) ((View)v.getParent()).findViewById(R.id.memberInfo);
		String[] info=t.getText().toString().split(" ");

		String requestMes=REQUEST+"|"+myProfile.getUserName()+"|"+myProfile.getEmail()+"|"
			+myProfile.getGender()+"|"+myProfile.getMacAddr()+"|"+myProfile.getPhoneNm();
		try {
			beddernetService.sendUnicast(info[1], null, requestMes.getBytes(), applicationIdentifier);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			Log.e(TAG,"Sending request to "+info[1]+" fails!");
		}
	}
	
	public void showMemberList(View v){
		if(memberList.getVisibility()!=0){
			friendList.setVisibility(4);
			friends.setVisibility(4);
			memberList.setVisibility(0);
			peers.setVisibility(0);
			getMembersInfo();
		}
	}
	
	public void showFriendList(View v){
		friendList.setVisibility(0);
		friends.setVisibility(0);
		memberList.setVisibility(4);
		peers.setVisibility(4);
	}
	
	public void removeFriend(View v){
		final TextView t=(TextView) ((View)v.getParent()).findViewById(R.id.friendId);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		Log.d(TAG,"remove friend " + t.getText().toString()+" from database...");
		builder.setMessage("Are you sure you want to remove?")
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   Toast.makeText(FriendActivity.this, "not implemented",  Toast.LENGTH_SHORT);
		        	   //getContentResolver().delete(Constant.PROFILE_CONTENT_URI, t.getText().toString(), null);
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		}).show();
		AlertDialog alert = builder.create();
	}
	
	public void onPause(){
		super.onPause();
		//stop the getMembersinfo thread, we don't need to update the Member list any more
		stop=true;
		updating=null;
		Log.d(TAG,"updating all member info thread stopped");
	}
}
